/**
 * Copyright (c) 2011 Duy Truong <hduyudh@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.anonymous.dobrochan.minoriko;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;

import org.anonymous.dobrochan.ApiWrapper;
import org.anonymous.dobrochan.DobroApplication;
import org.anonymous.dobrochan.R;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

public class ImgViewActivity extends Activity {
    // The main controls on the form
    DanboImageView imView0, imView1;
    TimedImageView tmpImv0, tmpImv1;
    ProgressBar imgProgressBar, downloadProgressBar;
    ViewSwitcher switcher;
    AlertDialog tagsDialog = null;
    AlertDialog commentsDialog = null;

    boolean everything;
    private boolean pageWaiting;
    private ImgViewActivity imgViewActivity = this;
    private CountDownTimer timer = null;
    Post post;
    private Animation slide_out_right;
    private Animation slide_in_left;
    private Animation slide_out_left;
    private Animation slide_in_right;
    private ImgFetcher imgFetcher = null;

    private boolean destroying;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        setContentView(R.layout.imgview);
        imView0 = (DanboImageView) findViewById(R.id.imgview_imView0);
//        imView0.setPrevNextHandler(this);
        imView1 = (DanboImageView) findViewById(R.id.imgview_imView1);
//        imView1.setPrevNextHandler(this);

        switcher = (ViewSwitcher) findViewById(R.id.imgview_switcher);

        imgProgressBar = (ProgressBar) findViewById(
                R.id.imgview_imgProgressBar);
        downloadProgressBar = (ProgressBar) findViewById(
                R.id.imgview_downloadProgressBar);
        imgProgressBar.setVisibility(View.GONE);
        downloadProgressBar.setVisibility(View.GONE);

        slide_in_right = AnimationUtils.loadAnimation(
                this, R.anim.slide_in_right);
        slide_out_left = AnimationUtils.loadAnimation(
                this, R.anim.slide_out_left);
        slide_in_left = AnimationUtils.loadAnimation(
                this, R.anim.slide_in_left);
        slide_out_right = AnimationUtils.loadAnimation(
                this, R.anim.slide_out_right);

        Intent i = getIntent();
        Bundle extras = i.getExtras();
        everything = extras.getBoolean("everything");
        post = new Post(
        		this,
        		extras.getInt("w"),
        		extras.getInt("h"),
        		i.getStringExtra("sample"),
        		i.getStringExtra("preview"),
        		i.getStringExtra("file"),
        		i.getStringExtra("save_to")
        		);
        destroying = false;
    }

    @Override
    public void onResume() {
        super.onResume();
        DanboImageView imView = (DanboImageView) switcher.getCurrentView();
        imView.setPost(post);
        launchImgDownloader(imView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        destroying = true;

        imView0 = null;
        imView1 = null;
        tmpImv0 = null;
        tmpImv1 = null;
        imgProgressBar = null;
        downloadProgressBar = null;
        switcher = null;
        if (tagsDialog != null) {
            tagsDialog.dismiss();
            tagsDialog = null;
        }

        commentsDialog = null;

        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (imgFetcher != null) {
            imgFetcher.cancel(true);
            imgFetcher = null;
            Toast.makeText(this, "Image download cancelled",
                    Toast.LENGTH_SHORT);
        }

        imgViewActivity = null;

        slide_out_right = null;
        slide_in_left = null;
        slide_out_left = null;
        slide_in_right = null;

    }

    public void launchImgDownloader(DanboImageView imView) {
    	imgProgressBar.setVisibility(View.GONE);
    	((DobroApplication) getApplication()).previewDownloader.download(
    			post.preview_url, imView.previewImgView);
    	((DobroApplication) getApplication()).imgDownloader.download(
    			post.sample_url,
    			imView, imgProgressBar);
    	Log.i("IMG/Sample", post.sample_url);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.imgview, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.imgmenu_save:
        {
        	File picsDir = new File(ApiWrapper.getDownloadDir());
    		Uri fileUri = Uri.parse("file://" + picsDir.getAbsolutePath()
    				+ File.separator + post.save_to);
        	ApiWrapper.download(Uri.parse(post.file_url), fileUri, post.save_to, this, false);
        }
            return true;
        case R.id.imgmenu_save_and_open:
        {
        	File picsDir = new File(ApiWrapper.getDownloadDir());
    		Uri fileUri = Uri.parse("file://" + picsDir.getAbsolutePath()
    				+ File.separator + post.save_to);
        	ApiWrapper.download(Uri.parse(post.file_url), fileUri, post.save_to, this, true);
        }
        	return true;
        case R.id.play_gif:
        {
        	DanboImageView imView = (DanboImageView)switcher.getCurrentView();
        	imView.setUrl(post.sample_url);
            if(post.sample_url != null && post.sample_url.endsWith(".gif")) {
            	try {
            		String fname = BitmapDownloaderTask.getFileName(this, post.sample_url);
    				imView.playGif(new FileInputStream(fname));
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
            }
        }
        	return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    public static boolean isSupported(String url) {
        return url.endsWith("jpg") || url.endsWith("jpeg") ||
                url.endsWith("png");
    }
}
